/**
 * $Revision: 1.0 $
 * $Author: Geln Yang $
 * $Date: May 19, 2010 10:32:40 PM $
 *
 * Author: Geln Yang
 * Date  : May 19, 2010 10:32:40 PM
 *
 */
package com.gooex.service.common.impl;

import java.util.List;

import org.c4j.net.NetTools;
import org.c4j.system.web.hibernate.BaseHibernateService;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import com.gooex.domain.common.Region;
import com.gooex.service.common.IRegionManager;


/**
 * @author Geln Yang
 * @version 1.0
 */
public class RegionManagerImpl extends BaseHibernateService implements IRegionManager {

	public Region getRegionByIp(String ipAddr) {
		try {
			long ip = NetTools.ip2long(ipAddr);
			String hql = "from " + Region.class.getName() + " where startip<=" + ip + " and endip>=" + ip
					+ " and length(id)=4";
			List<Region> result = getHibernateTemplate().find(hql);
			if (result != null && result.size() > 0)
				return result.get(0);
			else
				return getGlobalRegion();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return getGlobalRegion();
		}
	}

	public Region getGlobalRegion() {
		return getRegion(Region.GLOBAL_REGION);
	}

	public Region getRegion(String id) {
		return (Region) getHibernateTemplate().get(Region.class, id);
	}

	public List<Region> getTopRegions() {
		Criteria criteria = getSession().createCriteria(Region.class).setCacheable(true);
		criteria = criteria.add(Restrictions.or(Restrictions.isNull("parent"), Restrictions.eq("parent.id",
				Region.GLOBAL_REGION)));
		return criteria.list();
	}

}
